
const cheerio = require('cheerio');



const fs = require('fs')
const request = require('superagent');
require('superagent-charset')(request)

// 启动log
const log4js = require('log4js');
log4js.configure({
    appenders: { cheese: { type: 'file', filename: './getSDdata.log' } },
    categories: { default: { appenders: ['cheese'], level: 'trace' } }
});
const logger = log4js.getLogger('cheese');


// let num = $($($('.search-unit-list').find('tr')[2]).find('th')[0]).text()

var SDlist = [], downLoadCount = 0;
var weaponPicMap = {}, skillMap = {};

function getPageData(str, opt, cb) {
    var tmplist = []
    try {
        const $ = cheerio.load(str)
        $('.search-unit-list').each(function (index, ele) { //2
            $(ele).children('tbody').children('tr').each((index, ele) => {
                mkRobotData()
                function mkRobotData() {
                    if (index % 3 == 0) { //第一栏
                        let tmp = {
                            model: $($(ele).find('img')[0]).attr('alt'),
                            avatarURL: $($(ele).find('img')[0]).attr('src'),
                            rank: $(ele).find('.unit-rank').text(),
                            rating: $($(ele).find('.rating-value-small')).text(),
                            att: $($($(ele).find('tr')[2]).find('td')[0]).text(),
                            def: $($($(ele).find('tr')[2]).find('td')[1]).text(),
                            fly: $($($(ele).find('tr')[2]).find('td')[2]).text(),
                            ctl: $($($(ele).find('tr')[2]).find('td')[3]).text(),
                            D4sum: $($($(ele).find('tr')[2]).find('td')[4]).text(),
                            D3sum: $($($(ele).find('tr')[2]).find('td')[5]).text(),
                            ID: $($(ele).find('img')[0]).attr('src').match(/\d+\./)[0].slice(0, -1)
                        }
                        // save Avatar image
                        let avatarurl = 'http:' + tmp.avatarURL || ''
                        // get detail SDdata
                        let detailurl = `http://home.xhguo.net:41004/unit/${tmp.ID}?search`
                        request.get(avatarurl)
                            .then(res => {
                                saveAvatar(res)
                            })
                        getDetail(tmp)
                        function getDetail(tmp) {
                            console.log('开始获取' + tmp.model)
                            request.get(detailurl)
                                .then(res => {
                                    mergeData(tmp, res)
                                    SDlist.push(tmp)
                                    tmplist.push(tmp)
                                    console.log(`获取${tmp.model}机体成功`)
                                    logger.info(`获取${tmp.model}机体成功`)
                                    if (tmplist.length >= 10) {
                                        cb(true, SDlist)
                                    }
                                    if (SDlist.length >= opt.maxNum) {
                                        cb(true, SDlist)
                                    }
                                })
                                .catch(err => {
                                    console.log(`获取${tmp.model}失败，重新获取`)
                                    logger.info(`获取${tmp.model}失败，重新获取`)
                                    getDetail(tmp)
                                    // logger.error(err)
                                })
                        }

                        // fs.writeFileSync('./detail.js', detailData.text)


                    }
                    // if (index % 3 == 1) { //第二栏
                    // }
                    // if (index % 3 == 2) { //第三栏
                    //     SDlist.push(tmp);
                    // }
                }
            })
        })

    } catch (error) {
        console.log(error)
    }
}



function sleep(delay) {
    var start = (new Date()).getTime();
    while ((new Date()).getTime() - start < delay) {
        continue;
    }
}

function saveAvatar(res) {
    let avatarID = res.request.url.match(/\d+\./)[0].slice(0, -1)
    fs.writeFile('./img/Avatar/' + avatarID + '.png', res.body, (err) => {
        // err ? console.log(err) : console.log(`保存` + ++downLoadCount + `张图片`);
        err && console.log(err)
        ++downLoadCount
        if (downLoadCount % 10 == 0 || downLoadCount >= 750) {
            console.log(`保存` + downLoadCount + `张头像图片`);
            logger.info(`保存` + downLoadCount + `张头像图片`)
        }
    })
}

function mergeData(tmp, detailData) {
    const $ = cheerio.load(detailData.text)
    let weapon = []
    let weapon_detail = ''
    $("#t-weapon").find('tbody').children('tr').each((index, ele) => {
        $(ele).find('.weapon-ex-data').find('.weapon-ex-data').each((index, ele) => {
            weapon_detail += $(ele).text();
        })
        let oneWeapon = {
            weaponNum: $($(ele).find('.weapon-name')).text(),
            weaponName: $($(ele).find('div')[1]).text(),
            weapon_p: $($(ele).find('.weapon-p')).text(),
            weapon_e: $($(ele).find('.weapon-e')).text(),
            weapon_detail: weapon_detail,
            weapon_img: $($(ele).find('img')).attr('src')
        }
        weapon.push(oneWeapon)
        // download wewapon img.
        let img_id = $($(ele).find('img')).attr('src').match(/\d+\.gif/)[0]
        if (!weaponPicMap[img_id]) {
            let url = $($(ele).find('img')).attr('src')
            weaponPicMap[img_id] = url
        }
    })


    // 技能获取
    let skill = []
    $("#t-skill").find('tbody').children('tr').each((index, ele) => {
        oneSkill = {
            skill_img: $(ele).find('img').attr('src'),
            skill_name: $($(ele).find('span')[0]).text(),
            skill_detail: formatStringTrim($($($(ele).find('td')[1]).remove('.skill-name')).text(), { space: true }),
        }
        skill.push(oneSkill)
        // download skill img.
        let skill_id = $($(ele).find('img')).attr('src').match(/\d+\.gif/)[0]
        if (!skillMap[skill_id]) {
            let url = $($(ele).find('img')).attr('src')
            skillMap[skill_id] = url
        }
    })

    // 合成需求
    var makeNeed = [], toMake = [];
    $('#unit-mixing').children('li').each((index, ele) => {
        let tmp = {
            role: $($(ele).find('span')[0]).attr('class'),
            img: $(ele).find('img').attr('src'),
            Level: $($(ele).find('.level')).text(),
            rank: $($(ele).find('.rank')).text(),
            id: $($(ele).find('a')).attr('href').match(/\d+$/)[0],
            name: $(ele).find('img').attr('alt')
        }
        makeNeed.push(tmp)
    })
    $('#unit-mixing2').children('li').each((index, ele) => {
        let tmp = {
            role: $($(ele).find('span')[0]).attr('class').slice(-6, -1),
            img: $(ele).find('img').attr('src'),
            Level: $($(ele).find('.level')).text(),
            rank: $($(ele).find('.rank')).text(),
            id: $($(ele).find('a')).attr('href').match(/\d+$/)[0],
            name: $(ele).find('img').attr('alt')
        }
        toMake.push(tmp)
    })


    let tmp2 = {
        landType: $('.unit-landform').text(),
        fightType: $($(".unit-info-l").find('tbody').children('tr')[2]).find('a').text(),
        deformation: $($($(".unit-info-l").find('tbody').children('tr')[3]).find('span')[0]).hasClass('unit-func-on') ? true : false,
        repair: $($($(".unit-info-l").find('tbody').children('tr')[3]).find('span')[1]).hasClass('unit-func-on') ? true : false,
        Huge: $($($(".unit-info-l").find('tbody').children('tr')[3]).find('span')[2]).hasClass('unit-func-on') ? true : false,
        Sniper: $($($(".unit-info-l").find('tbody').children('tr')[3]).find('span')[3]).hasClass('unit-func-on') ? true : false,
        weapon: weapon,
        skill: skill,
        story: formatStringTrim(($('#unit-story').text())),
        Machine: $('#unit-getway-container').text().match(/\d+号/g),
        force: formatStringTrim($($($('#unit-extra-1').find('tr')[0]).remove('strong')).text()),
        feature: formatStringTrim($($($('#unit-extra-1').find('tr')[2]).remove('strong')).text()),
        from: formatStringTrim($($($('#unit-extra-1').find('tr')[3]).remove('strong')).text()),
        pilot: formatStringTrim($($($('#unit-extra-1').find('tr')[4]).remove('strong')).text()),
        mergeMap: $($($('#unit-extra-1').find('tr')[5]).find('a')).attr('href') || false,
        makeNeed: makeNeed,
        toMake: toMake
    }

    tmp = Object.assign(tmp, tmp2)
}


function getOtherPics() {
    var picArr = JSON.parse(fs.readFileSync('./otherPicJSON.json'))
    weaponPicMap = picArr[0]
    skillMap = picArr[1]
    var arrWeapon = [], arrSkill = [], i = 1, j = 1
    for (const id in weaponPicMap) {
        if (weaponPicMap.hasOwnProperty(id)) {
            const url = 'http:' + weaponPicMap[id];
            arrWeapon.push({
                url: url,
                id: id
            })
        }
    }
    for (const id in skillMap) {
        if (skillMap.hasOwnProperty(id)) {
            const url = 'http:' + skillMap[id];
            arrSkill.push({
                url: url,
                id: id
            })
        }
    }
    console.log(arrWeapon.length, arrSkill.length)

    getWeapon(i)
    getskill(j)
    function getWeapon(i) {
        let url = arrWeapon[i].url
        let id = arrWeapon[i].id
        console.log(`开始获取武器${id}`)
        request.get(url)
            .then(res => {
                console.log(`武器${id}OK`)
                fs.writeFile('./img/weapon/' + id, res.body, (err) => {
                    if (err) {
                        logger.info(`存储weapon图片失败，编号${id}`)
                    }
                    logger.info(`weapon-${id}成功`)
                })
                if (i < arrWeapon.length) {
                    i++
                    getWeapon(i)
                }
            })
            .catch(err => {
                console.log(`武器获取失败，号码${id}`)
                logger.error(`武器获取失败，号码${id}`)
                getWeapon(i)
            })
    }


    function getskill(j) {
        let url = arrSkill[j].url
        let id = arrSkill[j].id
        console.log(`开始获取skill${id}`)
        request.get(url)
            .then(res => {
                console.log(`skill-${id}OK`)
                if (j < arrSkill.length) {
                    j++
                    getskill(j)
                }
                fs.writeFile('./img/skill/' + id, res.body, (err) => {
                    if (err) {
                        logger.info(`存储skill图片失败，编号${id}`)
                    }
                    logger.info(`存储skill-${id}成功`)
                })

            })
            .catch(err => {
                console.log(`skill获取失败，号码${id}`)
                logger.error(`skill获取失败，号码${id}`)
                getskill(j)
            })
    }

}


function formatStringTrim(str, opt) {
    str = str.replace(/\\n/g, " ")
    if (opt && opt.space) {
        str = str.replace(/\s+/g, "/ ")
        str = str.replace(/\/\s+$/g, " ")
    } else {
        str = str.replace(/\s+/g, "")
    }

    return str
}

var g_getter = {
    sleep: sleep,
    getPageData: getPageData,
    getOtherPics: getOtherPics,
}
module.exports = g_getter